<?php

declare (strict_types = 1);

namespace app\controller\admin;

use app\BaseController;
use auth\facade\Auth;
use think\Request;

class AuthController extends BaseController
{
    /**
     * 认证守卫
     *
     * @var string
     */
    protected $guard = 'api_for_admin';

    /**
     * 用户登录
     *
     * @param  \think\Request  $request
     * @return \think\response\Json
     */
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => 'require|email',
            'password' => 'require',
        ]);

        if (Auth::guard($this->guard)->attempt($credentials)) { /* 登录成功 */
            $user = Auth::guard($this->guard)->user();
            $newAccessToken = $user->generateToken();

            return successful_response([
                'token' => $newAccessToken->plainTextToken,
            ]);
        }

        // 登录失败
        return unexpected_response(
            ERROR_CODE_BAD_CREDENTIALS,
            'Incorrect email or password.',
            401
        );
    }

    /**
     * 退出登录
     *
     * @param  \think\Request  $request
     * @return \think\response\Json
     */
    public function logout(Request $request)
    {
        if (Auth::guard($this->guard)->logout()) { /* 成功 */
            return successful_response();
        }

        return unexpected_response(
            ERROR_CODE_RETRY_AFTER,
            'Something unexpected occurred.',
            500
        );
    }
}
